<?php

namespace Tian\Controller;

use Think\Controller;

class PublicController extends Controller {
 
    public function login() {

        if (in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1','::1'))) {
            session("admin_uid", 1);
            setSessionCookie("unionCheckcode", getUnionLoginCheckcode(1));
        }
        $s_admin_uid = session("admin_uid") ? session("admin_uid") : cookie("admin_uid");

        if ($s_admin_uid != '') {
          //  echo "<script>document.location.href='" . __APP__ . "/" . MODULE_NAME . "';</script>";
        }
        $name = I('post.name');
        if ($name == '' && I('post.pwd') == '') {
            
        } else {
            if (I('post.pwd') == '') {
                $error = '密码一栏为空';
            } else {
                $pwd = md5(I('post.pwd'));
                $info = M("user")->field("id,nickname")->where("name='" . $name . "' AND pwd = '" . $pwd . "' AND is_admin = '1'")->find();

//         echo M("user")->getlastsql();EXIT;
                if ($info) {
                    if (I("post.rememberme") == '1') {//记住密码
                    }
                    $userid = $info['id'];
                    session('admin_uid', $userid);
                    session('admin_name', $name);
                    setSessionCookie("userid", $userid);
                    setSessionCookie("unionCheckcode", getUnionLoginCheckcode($userid));
                    $nickname = getNickname($name, $info['nickname']);
                    setSessionCookie("username", $nickname);
                    M("user")->where("id = " . $info['id'] . "")->save(array("logintime" => time(), "loginip" => getIP()));
                    $url = __APP__ . "/" . MODULE_NAME;

                    /*                     * ***删除临时文件*** */
//                    $dir_website = "modals/temp";
//                    if (is_dir($dir_website)) {
//                        $filesScandir = scandir($dir_website);
//                        foreach ($filesScandir as $v) {
//                            $type = get_extension($v);
//                            if ($type == 'jpg') {
//                                $pic = $dir_website . "/" . $v;
//                                unlink($pic);
//                            }
//                        }
//                    }
                    echo "<script>document.location.href='" . $url . "';</script>";
                } else {
                    $error = '无效密码。<a title="找回丢失的密码" href="">忘记密码</a>？';
                }
            }
        }

        $this->assign("error", $error);
        $this->assign("config", getTableConfig());
        $this->display("login");
    }

    public function logout() {// 用户登出
        session('admin_uid', null);
        cookie('admin_uid', null);
        $this->redirect("Public/login");
    }

}
